<template>
  <n-drawer
    v-model:show="modelValue.flag"
    :width="502"
    :height="500"
    :placement="'bottom'"
  >
    <n-drawer-content
      :title="'设置'"
      closable
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        :size="'medium'"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        :style="{
          maxWidth: '640px',
        }"
      >
        <n-form-item
          label="文件路径"
          path="dataPath"
        >
          <n-input
            v-model:value="formValue.dataPath"
            placeholder="选择路径"
            :disabled="true"
          />
          <n-button
            attr-type="button"
            @click="editPath"
            >选择文件夹</n-button
          >
        </n-form-item>
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick"
          >
            确定
          </n-button>
        </n-form-item>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script setup lang="ts" generic="T extends object & { flag:boolean, hello: string, world?: number }">
import UseSetting from "@pinias/UseSetting";
import { useMessage } from "naive-ui";
import type { FormInst } from "naive-ui";
import { ref, computed, watch } from "vue";

const { chooseDir, getSetting, setSetting } = UseSetting();
const message = useMessage();

// 父组件数据
const props = defineProps<{ modelValue: T }>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});

// 页面数据
const getNewFormValue = () => {
  let setting = Object.assign({}, getSetting());
  return setting;
};
const formValue = ref(getNewFormValue());
watch(
  //也可以第一参数为响应式数据
  modelValue.value,
  () => {
    formValue.value = getNewFormValue();
  },
);

// 限制规则
const formRef = ref<FormInst | null>(null);
const rules = {
  dataPath: {
    required: true,
    message: "请选择路径",
    trigger: ["input"],
  },
};

// 添加逻辑
// 选择文件地址
const editPath = async () => {
  const path = await chooseDir();
  if (path.length > 0) {
    formValue.value.dataPath = path;
  }
};
const save = () => {
  setSetting(formValue.value);
};
const changeFlag = () => (modelValue.value.flag = false);
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(errors => {
    if (!errors) {
      save();
      changeFlag();
      message.success("保存成功");
    } else {
      console.log("errors", formRef);
      message.error("不符合要求");
    }
  });
};
</script>

<style scoped></style>
